package org.jeecg.modules.yw.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.yw.entity.*;
import org.jeecg.modules.yw.mapper.AppointmentMapper;
import org.jeecg.modules.yw.mapper.OrderMapper;
import org.jeecg.modules.yw.mapper.OrderQueryMapper;
import org.jeecg.modules.yw.mapper.PagerInfoMapper;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.vo.EnterPriseVo;
import org.jeecg.modules.yw.vo.OrderQueryVO;
import org.jeecg.modules.yw.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;



@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> {
	//写几个枚举在当前类调用的
	private static  final String cshs = "查询核数不相符";
	private static  final String dkfc = "洞口复测不相符";
	private static  final String azbzwc = "安装班组完成";
	private static  final String djshwc = "打胶售后完成";
	private static  final String jsdqr = "结算待确认";
	private static  final String qgdjpd = "请给打胶售后派单";


    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderQueryMapper orderQueryMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private PagerInfoMapper pageInfoMapper;

    @Autowired
    private FileInfoService fileInfoService;
    
    @Autowired
    private MessagesService messageService;
    
    @Autowired
    private EnterPriseService enterpriseService;

	@Autowired
	private SysAnnoucementService sysAnnoucementService;
	@Autowired
	private IRulerpaperService rulerpaperService;
	
	@Autowired
	private FlPriceService flPriceService;

	@Autowired
    private IWorkerCompanyRelationService workRelationService;

	public int addOrder(Order order) {
    	String id = CommonUtils.getID();
    	order.setId(id);
    	order.setCreateTime(DateUtils.getCurrentTimeDateStr());
    	order.setCurrentUserId("0");
    	order.setState(0);
    	order.setDelFlag(0);
    	order.setOrderNo(this.createNewBidNumber());
    	String areas = "0";
    	
    	for (PaperInfo obj : order.getPageInfoList()) {
    		if (StringUtils.isNotBlank(obj.getArea())) {
    			areas = new BigDecimal(areas).add(new BigDecimal(obj.getArea())).toString();
    		}
    	}    	
    	areas = new BigDecimal(areas).setScale(2, RoundingMode.HALF_UP).toString();
    	order.setAreas(areas);
    	int success = orderMapper.inserOrder(order);
        String workerIds = workRelationService.getWorkersByCompanyId(order.getCreateUserId());
        EnterPrise enterPrise = enterpriseService.getById(order.getCreateUserId());
//    	Messages obj = new Messages();
//    	obj.setId(CommonUtils.getID());
//    	obj.setOrderId(id);
//    	obj.setOrderNo(order.getOrderNo());
//    	obj.setOwnerAddress(order.getOwnerAddress());
//    	obj.setYyTime(order.getYyTime());
//    	obj.setMsgType(1);
//    	obj.setOrderMsgType(0);
//    	obj.setState(0);
//    	obj.setMsgTime(DateUtils.getCurrentTimeDateStr());
//    	obj.setCurrentUserId("0");
//    	obj.setDelFlag(0);
    	//messageService.save(obj);   	
		sysAnnoucementService.AddSysAnnoucement("门窗企业新建订单消息", "新建订单消息-订单编号:"+order.getOrderNo()+",业主联系地址:"+order.getOwnerAddress()+",预约时间:"+order.getYyTime(), "4",order.getCreateUserId(), workerIds, order.getId(),"0", order.getOrderNo(), enterPrise.getCityCode());
        return success;
    }   
    

    public String createNewBidNumber() { //传的是2020-11-11
        String newBidDate = DateUtils.getDateStr();
        String orderId = orderMapper.createNewBidNumber(newBidDate);//根据传进来的日期向数据表中查询数据
        if (orderId != null){// 在数据表中查到了，说明现在这个订单不是今天的第一单
            String id = orderId.substring(8,11); // 取出后三位数，也就是自动生成的三位数 123
            int num = Integer.valueOf(id); 
            num ++;  // 123+1
            if(num<10){  
                String idNum = String.format("%03d", num);  //num<10,说明是个位数，前面要补两个0
                String date = newBidDate + idNum;
                date = date.replace("-", "");
                return date;
            }
            else if(num<100){
                String idNum = String.format("%03d", num);//num<100,说明是两位数，前面要补一个0
                String date = newBidDate + idNum;
                date = date.replace("-", "");
                return date;
            }
            else {
                String idNum = String.valueOf(num);
                String date = newBidDate + idNum;  //date = 20201111+124
                date = date.replace("-", "");
                return date;
            }
        } else {
            int number = 1;
            String idNum = "00" + number;
            String date = newBidDate + idNum;
            date = date.replace("-", "");
            return date;
        }
    }
    
    public Integer getMsgByCurrentUserId(String userId) {
    	List<Order> list = orderMapper.getOrderList(userId);
    	if (list != null && list.size() > 0) {
    		return 1;
    	} 
        return 0;
    }  
    
    
    
    public Integer getZyOrderList(String userId) {
    	List<Order> list = orderMapper.getZyOrderList(userId);
    	if (list != null && list.size() > 0) {
    		return 1;
    	} 
        return 0;
    }  
    
    /**
     * 添加预约人
     * @param list
     * @return
     */
    public int addAppointment(List<Appointment> list) {    	
    	for (Appointment obj : list) {
    		Order order = orderMapper.getOrder(obj.getOrderId());
	    	String id = CommonUtils.getID();
	    	obj.setId(id);
	    	obj.setAppointType("0");
	    	obj.setCreateTime(DateUtils.getCurrentTimeDateStr());
	    	obj.setAppointTime(order.getYyTime());
	    	appointmentMapper.insertAppointment(obj);	    	
	    	Messages message = new Messages();
	    	message.setId(CommonUtils.getID());	    	
	    	message.setOrderId(obj.getOrderId());
	    	message.setOrderNo(order.getOrderNo());
	    	message.setYyTime(order.getYyTime());
	    	message.setOwnerAddress(order.getOwnerAddress());
	    	message.setMsgType(1);
	    	message.setOrderMsgType(1);
	    	message.setState(0);
	    	message.setMsgTime(DateUtils.getCurrentTimeDateStr());
	    	message.setCurrentUserId(obj.getAppointId());
	    	message.setDelFlag(0);	    	
	    	messageService.save(message);
    	}
        return 0;
    }   
    
    
    /**
     * 添加预约人
     * @param obj
     * @return
     */
    public int addAppointment(Appointment obj) {    	
	    return appointmentMapper.insertAppointment(obj);
     
    }   
    
    
    /**
     * 操作预约
     * @param obj
     * @return
     */
    public int accpAppointment(Appointment obj) {    	
    	appointmentMapper.updataeAppointment(obj);
        return 0;
    }   
    
    /**
     * 得到订单详情
     * @param id
     * @return
     */
	public Order getOrder(String id) {
		//传过来的 订单orderId
		Order order = orderMapper.getOrder(id);
		String djTime = order.getDjTime();
		String yyTime = order.getYyTime();
		String yyTimeYYMMDD = null;
		if(StringUtils.isNotBlank(yyTime)&&yyTime.length()>10){
			yyTimeYYMMDD =DateUtils.convertToDate(yyTime);
		}
		String djTimeYYMMDD = null;
		if(StringUtils.isNotBlank(djTime)&&djTime.length()>10){
			djTimeYYMMDD =DateUtils.convertToDate(djTime);
		}
		order.setYyTime(yyTimeYYMMDD);
		//order.setDjTime(djTimeYYMMDD);
		if (order == null) {
			return null;
		}
		// 获取图纸信息
		Map<String, Object> map = new HashMap<>();
		map.put("orderId", id);
		String totalPrice = "0";
		List<PaperInfo> pageInfoList = pageInfoMapper.selectByMap(map);
		for (PaperInfo paper:pageInfoList) {
			Date date = DateUtils.strToDate(paper.getCreateTime());
			paper.setCreateTime(DateUtils.dateToStr(date));
			if (StringUtils.isNotBlank(paper.getPaperPrice())) {
				totalPrice = CommonUtils.addPrice(totalPrice, paper.getPaperPrice());
			}
		}
		order.setPageInfoList(pageInfoList);
		// 获取预约人员信息 通过这个orderId 查不到预约人员
		List<Appointment> personList = appointmentMapper.selectAppointsByOrderId(id);
		LinkedHashMap<String,List<Appointment>> personMa = new LinkedHashMap<>();
		String lastPersonId = null;
		List<Appointment> appointmentList = new ArrayList<>();
		for (Appointment vo : personList) {
			List<Appointment> newPersonList = null;
			String atime=vo.getAppointTime();
			if (StringUtils.isNotBlank(atime)) {
				atime = atime.substring(0, 10);
			}
			newPersonList=personMa.get(atime);
			if (newPersonList == null) {
				newPersonList = new ArrayList<>();
			}
			if (!StringUtils.equals(lastPersonId, vo.getId())) {
				newPersonList.add(vo);
				appointmentList.add(vo);
				lastPersonId = vo.getId();
			}
			personMa.put(atime, newPersonList);
		}
		List<Peo> personMap=new ArrayList<>();
		if(!personMa.isEmpty()){
			for (String key:personMa.keySet()) {
				Peo peo=new Peo();
				peo.setDate(key);
				peo.setPersonList(personMa.get(key));
				personMap.add(peo);
			}
		}
		order.setAppointmentMap(personMap);
		order.setPersonList(appointmentList);

		// 获取文件信息
		List<FileInfo> fileInfoList = fileInfoService.getFileInfoList(id);
		order.setFileInfoList(fileInfoList);
		String bzzHead = "";
		String bzzName = "";
		String djshName = "";
		String djshHead = "";
		// 获取班组长名称和头像
		if (StringUtils.isNotBlank(order.getAzbzUserId()) && !order.getAzbzUserId().equals("0")) {
			EnterPrise en = enterpriseService.getById(order.getAzbzUserId());
			bzzName = en.getName();
			bzzHead = en.getPicture();
			order.setBzzName(bzzName);
			order.setBzzHead(bzzHead);
		}
		if (StringUtils.isNotBlank(order.getDjshUserId()) && !order.getDjshUserId().equals("0")){
			EnterPrise dj = enterpriseService.getById(order.getDjshUserId());
			djshName = dj.getName();
			djshHead = dj.getPicture();
			order.setDjshName(djshName);
			order.setDjshHead(djshHead);
		}
		
	    FlPrice obj = flPriceService.getAllInfoByEnterpriseId(order.getCreateUserId());
        if (obj == null) {
        	obj = flPriceService.getFlPriceById(1);
        }	        
		String gbdkPrice = obj.getGbdkPrice();
		String gfccPrice = obj.getGfccPrice();
		String wgscPrice = obj.getWgscPrice();		
		// 改变洞口尺寸
		if (order.getCc() != null && order.getCc() == 1) {
			String gbdk = CommonUtils.MultiPrice(gbdkPrice, order.getCcNum()==null?0:order.getCcNum());
			order.setGbdkPrice(CommonUtils.Keep2Bits(gbdk));			
			totalPrice = CommonUtils.addPrice(totalPrice, gbdk);
		} else {
			order.setGbdkPrice("0.00");		
		}
		// 工费拆除价格
		if (order.getCclx() != null && order.getCclx() == 3) {
			String gfcc = CommonUtils.MultiPrice(gfccPrice, order.getCcfsNum()==null?0:order.getCcfsNum());
			order.setGfccPrice(CommonUtils.Keep2Bits(gfcc));			
			totalPrice = CommonUtils.addPrice(totalPrice, gfcc);
		}  else {
			order.setGfccPrice("0.00");		
		}
		// 产品搬运超大窗吊车卸车价格
		if (order.getCpby() != null && order.getCpby().contains("4")) {
			String cpby = obj.getCpbyPrice();
			order.setCpbyPrice(CommonUtils.Keep2Bits(cpby));			
			totalPrice = CommonUtils.addPrice(totalPrice, cpby);
		} else {
			order.setCpbyPrice("0.00");		
		}
		// 是否含外挂纱窗
		if (order.getWgsc() != null && order.getWgsc() == 1) {
			String wgsc = CommonUtils.MultiPrice(wgscPrice, order.getWgscNum()==null?0:order.getWgscNum());
			order.setWgscPrice(CommonUtils.Keep2Bits(wgsc));			
			totalPrice = CommonUtils.addPrice(totalPrice, wgsc);
		} else {
			order.setWgscPrice("0.00");		
		}		
		// 施工环境
		if (order.getSghj() != null && order.getSghj() == 0) {
			String sghj = obj.getSghjPrice();
			order.setSghjPrice(CommonUtils.Keep2Bits(sghj));			
			totalPrice = CommonUtils.addPrice(totalPrice, sghj);
		} else {
			order.setSghjPrice("0.00");		
		}		
		if (StringUtils.isNotBlank(totalPrice)) {
			order.setTotalPrice(CommonUtils.Keep2Bits(totalPrice));
		} else {
			order.setTotalPrice("0.00");
		}	
		return order;
	}
    
    
    
    /**
     * 
     * @param obj
     * @return
     */
    public List<Appointment> selectAppointAccpt(Appointment obj) {    	
    	List<Appointment> list = appointmentMapper.selectAppointAccpt(obj);
        return list;
    }   
    
    public List<EnterPriseVo> selectAppointAvailable(String yyTime,String bzzId, String cityCode) {
    	return appointmentMapper.selectAppointAvailable(yyTime,bzzId, cityCode);
    }
    
    public List<EnterPriseVo> selectAppointsByAppointTimeAndOrderId(String bzzId, String appointTime, String orderId) {
    	return appointmentMapper.selectAppointsByOrderIdAndAppointTime(bzzId, appointTime, orderId);
    }
    
    /**
     * 更新预约状态
     * @param order
     * @return
     */
    public int updateStatus(Order order) {
//		UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
//		wrapper.lambda().eq(Order::getOrderNo,order.getOrderNo())
//						.set(Order::getOrderStatus, order.getOrderStatus())//订单状态
//						.set(Order::getAzsgStatus, order.getAzsgStatus())//安装班组状态
//						.set(Order::getDjshStatus, order.getDjshStatus());//打胶售后状态
//		int update = orderMapper.update(order, wrapper);
		return orderMapper.updateStatus(order.getOrderStatus(), order.getAzsgStatus(), order.getDjshStatus(), order.getId());
    }   
    
    public int updateOrderInfo(Order order) {
		Order o = orderMapper.getOrder(order.getId());
		EnterPrise ent = enterpriseService.getById(o.getAzbzUserId());
		EnterPrise currentUser = enterpriseService.getById(order.getUserId());
		String cityCode=null;
		if(currentUser!=null){
			cityCode=currentUser.getCityCode();
		}
		Messages message = new Messages();
		message.setId(CommonUtils.getID());
		message.setOrderId(o.getId());
		message.setOrderNo(o.getOrderNo());
		message.setYyTime(o.getYyTime());
		message.setOwnerAddress(order.getOwnerAddress());
		message.setMsgType(2);
		message.setState(0);
		message.setMsgTime(DateUtils.getCurrentTimeDateStr());
		message.setCurrentUserId(o.getCreateUserId());
		message.setDelFlag(0);
		String workerIds = workRelationService.getWorkersByCompanyId(o.getCreateUserId());
		if (order.getCshs() != null && order.getCshs() == 0) {
    		order.setMcschsState(1);
    		order.setZkschsState(1);
			message.setId(CommonUtils.getID());
			message.setNormalMsgType(2);
			message.setRemark("订单编号:"+o.getOrderNo()+"\n"+ " 反馈问题人:"+ent.getName() +"\n"+
				" 查损核数反馈内容:"+order.getCshsContent());
			sysAnnoucementService.AddSysAnnoucement("安装班组反馈问题订单", "订单编号:"+o.getOrderNo()+ "反馈问题人:"+ent.getName()+
					"查损核数反馈:"+order.getCshsContent(), "8",o.getAzbzUserId(), workerIds, order.getId(),"1", o.getOrderNo(), cityCode);
			messageService.save(message);
		}
    	if (order.getDkfc() != null && order.getDkfc() ==  2) {
    		order.setMcdkfcState(1);
    		order.setZkdkfcState(1);
			message.setId(CommonUtils.getID());
			message.setNormalMsgType(1);
			message.setRemark("订单编号:"+o.getOrderNo()+"\n"+" 反馈问题人:"+ent.getName()+"\n"+
					" 洞口复测反馈内容:"+order.getDkfcContent());
			sysAnnoucementService.AddSysAnnoucement("安装班组反馈问题订单", "订单编号:"+o.getOrderNo()+ " 反馈问题人:"+ent.getName()+
					" 洞口复测反馈:"+order.getDkfcContent(), "8", o.getAzbzUserId(), workerIds, order.getId(),"1", o.getOrderNo(),cityCode);
			messageService.save(message);
		}
    	if (order.getAzsgStatus() != null && order.getAzsgStatus() == 8) {
			order.setOrderStatus(5);
			sysAnnoucementService.AddSysAnnoucement("安装班组完成消息", "订单编号:" + o.getOrderNo() + "反馈问题人:" + ent.getName() +
					" " + azbzwc, "9", o.getAzbzUserId(), workerIds, order.getId(), "0", o.getOrderNo(), cityCode);
			//没有同时给打胶派单
			if (o.getDjshUserId() == null || o.getDjshUserId().equals("0")) {
				//判断中控给打胶派单了，但是打胶未处理 或者拒绝的情况
				//假设未处理：查一下消息记录，看是否给打胶派过单，和中控派给打胶同时被拒绝的时候，则给中控发消息 新派打胶处理，如果有记录证明打胶未处理消息，
				List<Messages> list = messageService.getMessages(order.getId());
				//int i = sysAnnoucementService.getDjShJjMessageList(order.getId());
				if ((list == null || list.size() == 0)) {
					order.setState(1);
					sysAnnoucementService.AddSysAnnoucement("打胶售后待接单消息", "订单编号:" + o.getOrderNo() + qgdjpd, "18", o.getCreateUserId(), workerIds, order.getId(), "18", o.getOrderNo(), currentUser.getCityCode());
				}

			}
		}
    	// 告知售后2
//    	if (order.getGzsh2() != null && order.getGzsh2() == 4) {
//			if (order.getDjTime()!=null&& order.getDjTime()!=""){
//				order.setDjTime(order.getDjTime());
//			}
//    	}

		if (order.getDjshStatus()!=null  && order.getDjshStatus() == 2) {
			List<String> remarks = new ArrayList<>();
			String orderNo = o.getOrderNo();
			if (order.getNwlhs() != null && order.getNwlhs() == 1) {
//				sysAnnoucementService.AddSysAnnoucement("内外铝消息", orderNo + "内外铝划伤", "8", o.getDjshUserId(), workerIds, order.getId(), "3", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 内外铝有划伤");
			}
			if (order.getMshs() != null && order.getMshs() == 1) {
//				sysAnnoucementService.AddSysAnnoucement("门扇划伤消息", orderNo + "木材划伤", "8", o.getDjshUserId(), workerIds, order.getId(), "4", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 门扇有划伤");
			}
			if (order.getBlps() != null && order.getBlps() == 1) {
//				sysAnnoucementService.AddSysAnnoucement("玻璃破伤消息", orderNo + "玻璃破伤", "8", o.getDjshUserId(), workerIds, order.getId(), "5", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 玻璃破伤");
			}
			if (order.getPjwr() != null && order.getPjwr() == 1) { // 修正可能的笔误
//				sysAnnoucementService.AddSysAnnoucement("玻璃胶污染消息", orderNo + "玻璃胶污染地面", "8", o.getDjshUserId(), workerIds, order.getId(), "6", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 玻璃胶污染地面");
			}
			if (order.getKqsflw() != null && order.getKqsflw() == 0) {
//				sysAnnoucementService.AddSysAnnoucement("开启扇灵活消息", orderNo + "开启扇不灵活", "8", o.getDjshUserId(), workerIds, order.getId(), "7", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 开启扇不灵活");
			}
			if (order.getZskg() != null && order.getZskg() == 0) {
//				sysAnnoucementService.AddSysAnnoucement("执手扣盖消息", orderNo + "执手扣盖不齐全", "8", o.getDjshUserId(), workerIds, order.getId(), "8", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 执手扣盖不齐全");
			}
			if (order.getFpbm() != null && order.getFpbm() == 0) {
//				sysAnnoucementService.AddSysAnnoucement("发泡胶水消息", orderNo + "发泡胶水不饱满", "8", o.getDjshUserId(), workerIds, order.getId(), "9", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 发泡胶水不饱满");
			}
			if (order.getLjql() != null && order.getLjql() == 0) { // 修正可能的笔误
//				sysAnnoucementService.AddSysAnnoucement("清理垃圾消息", orderNo + "垃圾和包装物未清理干净", "8", o.getDjshUserId(), workerIds, order.getId(), "10", o.getOrderNo(), currentUser.getCityCode());
				remarks.add(orderNo + " 垃圾和包装物未清理干净");
			}
			if (!remarks.isEmpty()) {
				StringBuilder remarkBuilder = new StringBuilder();
				for (String remark : remarks) {
					remarkBuilder.append("\n").append(remark);
				}
				message.setId(CommonUtils.getID());
				message.setNormalMsgType(3);
				message.setCurrentUserId(o.getAzbzUserId());
				message.setRemark(remarkBuilder.toString());
				sysAnnoucementService.AddSysAnnoucement("质检反馈问题消息", remarkBuilder.toString(), "8", o.getDjshUserId(), workerIds, order.getId(), "10", o.getOrderNo(), currentUser.getCityCode());
				message.setMsgTime(DateUtils.getCurrentTimeDateStr());
				messageService.save(message);
			}
		}
//		if ((order.getDjshStatus() != null && order.getDjshStatus() == 5) || (order.getOrderStatus()!=null && order.getOrderStatus() == 8)) {
		if ( order.getDjshStatus() != null && order.getDjshStatus() == 5) {
    		order.setOrderStatus(8);
    		order.setDjFinishTime(DateUtils.getCurrentTimeDateStr());
			sysAnnoucementService.AddSysAnnoucement("打胶售后完成消息", "订单编号:"+o.getOrderNo()+djshwc, "13", o.getDjshUserId(), workerIds, order.getId(),"0", o.getOrderNo(), currentUser.getCityCode());
		}
//    	if (order.getOrderStatus()!=null && order.getOrderStatus() == 6) {
//			//
//			//要解决的问题： 判断安装班组完成后 此时打胶处于未接单状态，此时安装给中控发消息，让中控给打胶派单
//			//前传订单状态是6  现在打胶的状态是5 代表是打胶组待施工订单，需要判断消息的接收情况
//    				Messages message = new Messages();
//    		    	message.setId(CommonUtils.getID());
//    		    	message.setOrderId(o.getId());
//    		    	message.setOrderNo(o.getOrderNo());
//    		    	message.setYyTime(o.getYyTime());
//    		    	message.setOwnerAddress(order.getOwnerAddress());
//    		    	message.setMsgType(1);
//    		    	message.setOrderMsgType(4);
//    		    	message.setState(0);
//    		    	message.setMsgTime(DateUtils.getCurrentTimeDateStr());
//    		    	message.setCurrentUserId("0");
//    		    	message.setDelFlag(0);
//    		    	messageService.save(message);
//    		}
		if (order.getOrderStatus()!=null && order.getOrderStatus() == 9) {
			sysAnnoucementService.AddSysAnnoucement("结算确认", "订单编号:"+o.getOrderNo()+" "+jsdqr, "14", order.getCreateUserId(), workerIds, order.getId(),"11", o.getOrderNo(), currentUser.getCityCode());
		}
    	return orderMapper.updateOrderInfo(order);
    }


    public Order getOrderByOrderNo(String orderNo) {
        return orderMapper.getOrderByOrderNo(orderNo);
    }
    
//    /**
//     * 得到订单实时消息
//     * @param page
//     * @param queryWrapper
//     * @param userId
//     * @param roleId
//     * @param isLeader
//     * @return
//     */
//    public IPage<OrderQueryVO> getOderMsg(Page<OrderQueryVO> page, QueryWrapper<OrderQueryVO> queryWrapper, String userId, Integer roleId, Integer isLeader) {
//    	if (roleId == 1) {
//    		 queryWrapper.eq("currentUserId", userId);
//    		 queryWrapper.eq("state", 0);
//    	} else if (roleId == 2) {
//    		if (isLeader != null && isLeader == 1) {
//    			queryWrapper.eq("currentUserId", userId);
//    			queryWrapper.eq("state", 0);
//    		} else {
//    			queryWrapper.inSql("id", "select orderId from appointment where appointId = '"+userId+"' and delFlag = 0 and appointType = 0");
//    			queryWrapper.eq("state", 0);
//    		}   
//    	} else {
//	   		 queryWrapper.eq("currentUserId", userId);
//	   		 queryWrapper.eq("state", 0);
//    	}
//        queryWrapper.eq("delFlag", 0);
//        queryWrapper.orderByDesc("createTime");
//        return orderMapper.getAllOrders(page, queryWrapper);
//    }	 
//	 
    public IPage<OrderQueryVO> getOders(Page<OrderQueryVO> page, QueryWrapper<OrderQueryVO> queryWrapper, String userId, Integer roleId, Integer isLeader) {
	   	if (roleId == 1) {
	   		 queryWrapper.eq("createUserId", userId);
	   	} else if (roleId == 2) {
	   		if (isLeader != null && isLeader == 1) {
	   			queryWrapper.eq("azbzUserId", userId).or().inSql("id", "select orderId from appointment where bzzId = '"+userId+"'");
	   		} else {
	   			queryWrapper.inSql("id", "select orderId from appointment where appointId = '"+userId+"'");
	   		}   
	   	} else {
	   		queryWrapper.eq("djshUserId", userId);
	   	}
       queryWrapper.eq("delFlag", 0);
       queryWrapper.orderByDesc("updateTime");
       return orderQueryMapper.getAllOrders(page, queryWrapper);
   }    

    public IPage<OrderVo> getPage(IPage<OrderVo> page, Date start, Date end,
								  String orderStatus, String orderno, String cardid, String problem, String[] areas,
								  String[] enters,String name, String ownerPhone) {
        return orderMapper.getPage(page, start, end, orderStatus, orderno, cardid,problem,areas,enters, name, ownerPhone);
    }

	public IPage<Order> appointPage(IPage<Order> page, Date start, Date end) {
		QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
		if(start != null && end != null) {
			queryWrapper.between("createTime", start, end);
		}else if(start != null){
			queryWrapper.ge("createTime", start);
		} else if (end!=null) {
			queryWrapper.le("createTime", end);
		}
		queryWrapper.orderByDesc("createTime");
		IPage<Order> pageO= orderMapper.selectPage(page, queryWrapper);
		for (Order order:pageO.getRecords()){
//		    EnterPrise enterPrise =	enterPriseService.getBaseMapper().selectOne(new QueryWrapper<EnterPrise>().eq("id",order.getCreateUserId()));
//			order.setEnterpriseName(enterPrise.getName());
			QueryWrapper<Rulerpaper> queryWrapper1 = new QueryWrapper<>();
			queryWrapper1.eq("orderid",order.getId());
			queryWrapper1.orderByAsc("sorted");
		    List<Rulerpaper> rlist =rulerpaperService.list(queryWrapper1);
			List<String> list = new ArrayList<>();
			for (Rulerpaper r:rlist){
				list.add(r.getPageurl());
			}
			order.setRList(list);
		}
		return pageO;

	}
	public Order getOrderByOrderId (String orderId) {
		if (orderId != null&& !orderId.isEmpty()){
			return null;
		}
		QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("id", orderId).or()
				.like("orderNo", orderId);
		Order order = orderMapper.selectOne(queryWrapper);
		if (order == null) {
			return null;
		}
		return order;
	}
	
	
	/**
	 * 派单
	 * @param azbzUserId
	 * @param djshUserId
	 * @return
	 */
	public int zkpd(String orderId, String azbzUserId, String djshUserId) {
		Messages message = new Messages();
		Order order = orderMapper.getOrder(orderId);
		message.setId(CommonUtils.getID());
		message.setOrderId(orderId);
		message.setOrderNo(order.getOrderNo());
		message.setYyTime(order.getYyTime());
		message.setOwnerAddress(order.getOwnerAddress());
		message.setMsgType(1);
		message.setOrderMsgType(1);
		message.setState(0);
		message.setCurrentUserId(azbzUserId);
		message.setMsgTime(DateUtils.getCurrentTimeDateStr());
		message.setDelFlag(0);
		message.setReason(" ");
		if (StringUtils.isNotBlank(azbzUserId)) {
			messageService.getBaseMapper().insert(message);
		}
		if (StringUtils.isNotBlank(djshUserId)) {
			Messages m = new Messages();
			m.setId(CommonUtils.getID());
			m.setOrderId(orderId);
			m.setOrderNo(order.getOrderNo());
			m.setYyTime(order.getYyTime());
			m.setOwnerAddress(order.getOwnerAddress());
			m.setMsgType(1);
			m.setOrderMsgType(4);
			m.setState(0);
			m.setCurrentUserId(djshUserId);
			m.setMsgTime(DateUtils.getCurrentTimeDateStr());
			m.setDelFlag(0);
			m.setReason(" ");
			messageService.getBaseMapper().insert(m);
		}
		Order o = new Order();
		o.setId(orderId);
		o.setState(2);
		if (StringUtils.isNotBlank(azbzUserId)) {
			o.setAzbzReason(" ");
		}
		if (StringUtils.isNotBlank(djshUserId)) {
			o.setDjshReason(" ");
		}
		if (StringUtils.isNotBlank(azbzUserId) && StringUtils.isNotBlank(djshUserId)) {
			if (StringUtils.isBlank(order.getDjTime())) {
				o.setDjTime(order.getYyTime().substring(0,10));
			}
		}
		if (StringUtils.isNotBlank(azbzUserId)) {
			EnterPrise ent = enterpriseService.getById(azbzUserId);
			if (ent != null) {
				//o.setYpzzbz("安装班组人员:"+ent.getName() + "(已派暂未接受)");
				orderMapper.updateAzbz("安装班组人员:" + ent.getName() + "(已派暂未接受)", orderId);

			}
		}
		if (StringUtils.isNotBlank(djshUserId)) {
			EnterPrise ent = enterpriseService.getById(djshUserId);
			if (ent != null) {
				orderMapper.updateDjsh("打胶售后人员:" + ent.getName() + "(已派暂未接受)", orderId);
			}
		}

		if (StringUtils.isNotBlank(azbzUserId) || StringUtils.isNotBlank(djshUserId)) {
			orderMapper.updateOrderInfo(o);
		}
		return 1;
	}
	
	
	/**
	 * 中控结算
	 * @param azbzUserId
	 * @param djshUserId
	 * @return
	 */
	public int zkjs(String orderId, String path) {
		Order order = orderMapper.getOrder(orderId);
		
		Messages message = new Messages();
		message.setId(CommonUtils.getID());
		message.setOrderId(orderId);
		message.setOrderNo(order.getOrderNo());
		message.setYyTime(order.getYyTime());
		message.setOwnerAddress(order.getOwnerAddress());
		message.setMsgType(1);
		message.setOrderMsgType(7);
		message.setState(0);
		message.setCurrentUserId(order.getCreateUserId());
		message.setMsgTime(DateUtils.getCurrentTimeDateStr());
		message.setDelFlag(0);
		message.setReason(" ");
		message.setRemark(" ");
		messageService.save(message);		
		
		Order o = new Order();
		o.setId(orderId);
		o.setOrderStatus(9);	
		o.setJsPath(path);
		o.setJsReason(" ");
		orderMapper.updateOrderInfo(o);
		return 1;
	}
	
	
	/**
	 * 中控金额
	 * @param azbzUserId
	 * @param djshUserId
	 * @return
	 */
	public int confirmOrder(String orderId, String price) {
		Order order = new Order();
		order.setId(orderId);
		if (StringUtils.isNotBlank(price)) {
			order.setFinalPrice(price);
		}	
		order.setXgsj(DateUtils.getCurrentTimeDateStr());
		orderMapper.updateOrderInfo(order);
		return 1;
	}
	
	

	/**
	 * 中控付款
	 * @param azbzUserId
	 * @param djshUserId
	 * @return
	 */
	public int confirmPay(String orderId) {
		Order order = new Order();
		order.setId(orderId);
		// 11 已付款
		order.setOrderStatus(11);
		order.setFinishTime(DateUtils.getCurrentTimeDateStr());
		orderMapper.updateOrderInfo(order);
		return 1;
	}
	public OrderVo getByVoId(String id) {
		return orderMapper.getByVoId(id);
	}

    public static String createNewBidNumberTest() { //传的是2020-11-11
        String newBidDate = DateUtils.getDateStr();
        String orderId = "20250421009";//根据传进来的日期向数据表中查询数据
        if (orderId != null){// 在数据表中查到了，说明现在这个订单不是今天的第一单
            String id = orderId.substring(8,11); // 取出后三位数，也就是自动生成的三位数 123
            int num = Integer.valueOf(id); 
            num ++;  // 123+1
            if(num<10){  
                String idNum = String.format("%03d", num);  //num<10,说明是个位数，前面要补两个0
                String date = newBidDate + idNum;
                date = date.replace("-", "");
                return date;
            }
            else if(num<100){
                String idNum = String.format("%03d", num);//num<100,说明是两位数，前面要补一个0
                String date = newBidDate + idNum;
                date = date.replace("-", "");
                return date;
            }
            else {
                String idNum = String.valueOf(num);
                String date = newBidDate + idNum;  //date = 20201111+124
                date = date.replace("-", "");
                return date;
            }
        } else {
            int number = 1;
            String idNum = "00" + number;
            String date = newBidDate + idNum;
            date = date.replace("-", "");
            return date;
        }
    }
    
    public static void main(String args[]) {
    	String orderNo = createNewBidNumberTest();
    	System.out.println(orderNo);    	
    	String idNum = String.format("%03d", 9);//num<100,说明是两位数，前面要补一个0    	 
    	System.out.println(idNum);
    }
}



